package org.budo.redis.jdbc.driver.statement.server;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;

import org.budo.jdbc.driver.resultset.impl.MapArrayResultSet;
import org.budo.redis.jdbc.driver.BudoRedisJdbcConnection;
import org.budo.redis.jdbc.driver.BudoRedisJdbcPreparedStatement;
import org.budo.redis.jdbc.driver.BudoRedisJdbcResultSetMetaData;
import org.budo.redis.jdbc.driver.executor.RedisStatementExecutor;
import org.budo.redis.jdbc.driver.statement.AbstractRedisStatement;
import org.budo.support.lang.util.MapUtil;

/**
 * @author lmw
 */
public class CONFIG_GET extends AbstractRedisStatement {
    @Override
    public void execute(PreparedStatement preparedStatement) throws SQLException {
        byte[] pattern = this.parameter(0, preparedStatement);

        RedisStatementExecutor statementExecutor = ((BudoRedisJdbcConnection) preparedStatement.getConnection()).getStatementExecutor();
        byte[][] configGet = statementExecutor.configGet(pattern);

        Map[] valueArray = new Map[configGet.length / 2];
        for (int i = 0; i < valueArray.length; i++) {
            valueArray[i] = MapUtil.stringObjectMap("key", configGet[i * 2], //
                    "value", configGet[i * 2 + 1]);
        }

        BudoRedisJdbcResultSetMetaData metaData = new BudoRedisJdbcResultSetMetaData(new String[] { "key", "value" });
        MapArrayResultSet resultSet = new MapArrayResultSet(metaData, valueArray);
        ((BudoRedisJdbcPreparedStatement) preparedStatement).setResultSet(resultSet);
    }
}